package com.example.student.utils;

import com.example.student.entity.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class UserUtils {
    public static User getUser(){
        Claims claims = (Claims) getRequest().getAttribute("user_claims");
        User user = new User();
        user.setName(claims == null?"自主注册":claims.get("name",String.class));
        user.setId(claims == null?"1":claims.get("id",String.class));
        user.setRole(claims == null? 0 :claims.get("role",Integer.class));
        return user;
    }

    public static String getId(){
        return getUser().getId();
    }

    public static String getName(){
        return getUser().getName();
    }

    public static Integer getRole(){
        return getUser().getRole();
    }

    private static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    private static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }
}
